package com.xiaoxian.basic.interceptor;

import com.xiaoxian.basic.annotation.PreAuthorize;
import com.xiaoxian.basic.util.jwt.*;
import com.xiaoxian.org.mapper.EmployeeMapper;
import com.xiaoxian.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.xiaoxian.basic.util.jwt.JwtUtils.getInfoFromToken;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求体中获取token
        String header = request.getHeader("U-TOKEN");
        //判断token是否存在
        if(header!=null){
            //获取redis中的token
            //Object token = redisTemplate.opsForValue().get(header);
            //解密token获取加密的信息
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(header, publicKey, UserInfo.class);
            LoginInfo logininfo = payload.getUserInfo().getLoginInfo();
            //如果有就放行
            if(logininfo!=null){
                //获取要访问的方法上是否有PreAuthorize
                HandlerMethod method = (HandlerMethod)handler;
                //获取到注解
                PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                //如果获取到了
                if(methodAnnotation != null) {
                    //通过logininfo的id去查询他所有permssion的sn
                    //List<String> sns = permissionMapper.loadPermissionByLoginInfoId(lf.getId());
                    List<String> sns = payload.getUserInfo().getPermissions();
                    //比对查出来的sn是否有要校验接口注解上的sn
                    if (!sns.contains(methodAnnotation.value())) {
                        //没有返回没有权限
                        response.setCharacterEncoding("utf-8");
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        writer.write("{\"code\":401,\"success\":false,\"message\":\"noPermission\"}");
                        writer.flush();
                        writer.close();
                        return false;
                    }
                }
                //刷新token过期时间
                //redisTemplate.opsForValue().set(token,(Logininfo)logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //返回给前端ajaxresult
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"code\":401,\"success\":false,\"msg\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
